package com.core.sys.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.core.common.dao.Pager;
import com.core.common.pageModel.Combo;
import com.core.sys.dao.IUserDao;
import com.core.sys.entity.UserEntity;
import com.core.sys.service.IUserService;
import com.core.sys.vo.ActiveUserVo;
import com.core.sys.vo.RoleVo;
import com.core.sys.vo.UserVo;
import com.utils.DigestUtil;
import com.utils.date.DateUtil;
import com.utils.ehcache.CacheConstants;
import com.utils.ehcache.CacheManagerUtil;

@Service
public class UserServiceimpl implements IUserService {

	@Resource
	private IUserDao userDao;
	
	@Override
	@Transactional
	public void save(UserVo userDto) throws Exception {
		UserEntity user = new UserEntity();
		if (StringUtils.isNotBlank(userDto.getUserName())) {
			user.setUserName(userDto.getUserName());
			user.setEmail(userDto.getEmail());
			user.setMobile(userDto.getMobile());
			user.setPassWord(DigestUtil.getMD5(userDto.getPassWord()));
			user.setRealName(userDto.getRealName());
			user.setGender(userDto.getGender());
			user.setCreateUser(userDto.getCreateUser());
			user.setUpdateUser(user.getCreateUser());
			user.setCreateDate(new Date());
			user.setUpdateDate(user.getCreateDate());
			user.setVersion(1);
			userDao.save(user);			
		}
	}

	@Override
	@Transactional
	public void delete(String[] userIdArray) {
		List<Long> userIds = new ArrayList<Long>();
		for (String userId : userIdArray) {
			userIds.add(Long.parseLong(userId));
			//情况缓存
			CacheManagerUtil.getSingletonInstance().getCache(CacheConstants.CACHE_USERS).remove(Long.parseLong(userId));
			CacheManagerUtil.getSingletonInstance().getCache(CacheConstants.CACHE_USERS_GROUP).removeAll();
		}
		if(userIds.size() > 0){
			//伪删除用户，更新用户状态
			userDao.updateDeleteFlagByUserIds(userIds);			
		}
	}
	
	@Override
	@Transactional
	public void update(UserVo userDto) throws Exception {
		UserEntity user = userDao.get(userDto.getId());
		if (StringUtils.isNotBlank(userDto.getUserName())) {
			user.setUserName(userDto.getUserName());
			
			if (StringUtils.isNotBlank(userDto.getPassWord())) {
				user.setPassWord(DigestUtil.getMD5(userDto.getPassWord()));
			}
			if (StringUtils.isNotBlank(userDto.getEmail())) {
				user.setEmail(userDto.getEmail());
			}
			if (StringUtils.isNotBlank(userDto.getMobile())) {
				user.setMobile(userDto.getMobile());
			}
			if (StringUtils.isNotBlank(userDto.getRealName())) {
				user.setRealName(userDto.getRealName());
			}
			user.setGender(userDto.getGender());
			user.setUpdateUser(userDto.getUpdateUser());
			user.setUpdateDate(new Date());
			if(user.getVersion() != null){
				user.setVersion(user.getVersion() + 1);			
			}
			userDao.update(user);
		}
	}
	
	@Override
	public UserVo getUserByUserId(Long userId) {
		Object obj = CacheManagerUtil.getSingletonInstance().get(CacheConstants.CACHE_USERS, userId);
		if(null != obj)
			return (UserVo) obj;
		UserEntity user = userDao.get(userId);
		if(user != null){
			UserVo vo = this.pojoToDto(user, false); 
			CacheManagerUtil.getSingletonInstance().put(CacheConstants.CACHE_USERS, userId, vo);
			return vo;
		}
		return null;
	}
	
	@Override
	public String getUserGroupNames(String strUserIds) {
	    if(StringUtils.isNotBlank(strUserIds)){
	        Object obj = CacheManagerUtil.getSingletonInstance().get(CacheConstants.CACHE_USERS_GROUP, strUserIds);
	        if(null != obj)
	            return obj.toString();
	        String[] userIdArray = strUserIds.split(",");
	        Long[] userIds = new Long[userIdArray.length];
	        for (int i = 0; i < userIdArray.length; i++) {
	            userIds[i] = Long.parseLong(userIdArray[i]);
	        }
	        List<UserEntity> users = userDao.selectByUserIds(userIds);
	        Long[] consumeUserIds = new Long[users.size()];
	        for (int i = 0; i < users.size(); i++) {
	            consumeUserIds[i] = users.get(i).getId();
	        }
	        String strConsumeUserIds = StringUtils.join(consumeUserIds, ",");
	        CacheManagerUtil.getSingletonInstance().put(CacheConstants.CACHE_USERS_GROUP, strUserIds, strConsumeUserIds);
	        return strConsumeUserIds;
	    }
	    return null;
	}
	
	@Override
	public ActiveUserVo getActiveUserByName(String userName) throws Exception {
		ActiveUserVo acticeUser = new ActiveUserVo();
		//设置超级管理员
		if(userName.equals("admin")){
			acticeUser.setId(0);
			acticeUser.setUserName("admin");	
			acticeUser.setPassWord(DigestUtil.getMD5("admin@admin"));
			return acticeUser;
		}
		UserEntity user = userDao.getUserByName(userName);
		if(user != null){
			acticeUser.setId(user.getId());
			acticeUser.setUserName(user.getUserName());	
			acticeUser.setPassWord(user.getPassWord());
			return acticeUser;
		}
		return null;
	}
	
	@Override
	public Pager<UserVo> getUserList(int pageIndex, int pageSize, String userName,
			String createdateStart, String createdateEnd,String updatedateStart, 
			String updatedateEnd, String[] deptIds,String sort, String order) {
		if(pageIndex == 0){
			pageIndex = 1;
		}
		Set<Long> userIdSet = new HashSet<Long>();
		
		String sort_order = "";
		if(StringUtils.isNotBlank(sort) || StringUtils.isNotBlank(order)){
			sort_order = sort + " " + order;
		}
		List<UserVo> userModelList = new ArrayList<UserVo>();
		Pager<UserEntity> userPager = userDao.selectByOption(pageIndex, pageSize, userName, 
				createdateStart, createdateEnd, updatedateStart, updatedateEnd,userIdSet, sort_order);
		List<UserEntity> userList = userPager.getDatas();
		if(CollectionUtils.isNotEmpty(userList)){
			UserVo dto = null;
			for (UserEntity user : userList) {
				dto = this.pojoToDto(user,true);
				RoleVo role = new RoleVo();
				role.setName("管理员");
				dto.setRole(role);
				userModelList.add(dto);
			}
		}
		Pager<UserVo> pager = new Pager<UserVo>(pageIndex, pageSize, userPager.getTotalCount(), userModelList);
		return pager;			
	}
	

    @Override
    public Pager<UserVo> getUserList(String userName, String createdateStart,
            String createdateEnd, String updatedateStart, String updatedateEnd, String[] deptIds) {
        Set<Long> userIdSet = new HashSet<Long>();
        List<UserVo> userModelList = new ArrayList<UserVo>();
        Pager<UserEntity> userPager = userDao.selectByOption(userName, createdateStart,
                createdateEnd, updatedateStart, updatedateEnd,userIdSet);
        if(null != userPager){
            List<UserEntity> userList = userPager.getDatas();
            if(CollectionUtils.isNotEmpty(userList)){
                UserVo dto = null;
                for (UserEntity user : userList) {
                    dto = this.pojoToDto(user,true);
                    RoleVo role = new RoleVo();
                    role.setName("管理员");
                    dto.setRole(role);
                    userModelList.add(dto);
                }
            }
            return new Pager<UserVo>(userPager.getPageIndex(), userPager.getPageSize(), userPager.getTotalCount(), userModelList);
        }
        return null;
    }
    
	@Override
	public boolean existUserName(UserVo user) {
		List<UserEntity> list = userDao.findByParam("userName", user.getUserName());
		if(CollectionUtils.isNotEmpty(list)){
			if(user.getId() == 0){
				return true;				
			}else{
				if(user.getId() != list.get(0).getId()){
					return true;
				}
			}
		}
		return false;
	}
	
	private UserVo pojoToDto(UserEntity user,boolean isGetRole) {
		UserVo userDto = new UserVo();
		userDto.setId(user.getId());
		userDto.setUserName(user.getUserName());
		userDto.setPassWord(user.getPassWord());
		userDto.setMobile(user.getMobile());
		userDto.setEmail(user.getEmail());
		userDto.setCreateUser(user.getCreateUser());
		userDto.setCreateDate(DateUtil.format(user.getCreateDate()));
		if(isGetRole){
			userDto.setUserRole("");				
		}
		return userDto;
	}

	@Override
	public List<Combo> getUserComboList(long userId) {
		List<UserEntity> list = userDao.findByParam("deleteFlag", false, "id", null);
		if(CollectionUtils.isNotEmpty(list)){
			List<Combo> comboList = new ArrayList<Combo>(list.size());
			Combo combo = null;
			for (UserEntity userEntity : list) {
				combo = new Combo();
				combo.setValue(String.valueOf(userEntity.getId()));
				combo.setText(userEntity.getUserName());
				if(0 != userId && userEntity.getId() == userId)
					combo.setSelected(true);
				comboList.add(combo);
			}
			return comboList;
			
		}
		return null;
	}

}
